package com.kelvem.saas.workbanch.ontology.order.handle.core;

import com.kelvem.saas.workbanch.fsm.core.EventContext;
import com.kelvem.saas.workbanch.fsm.handle.Handle;
import com.kelvem.saas.workbanch.ontology.order.model.OrderAddressEntity;
import com.kelvem.saas.workbanch.ontology.order.model.OrderExtendEntity;
import com.kelvem.saas.workbanch.ontology.order.model.OrdersEntity;
import com.kelvem.saas.workbanch.ontology.order.request.OrderAddressReq;
import com.kelvem.saas.workbanch.ontology.order.request.OrderExtendReq;
import com.kelvem.saas.workbanch.ontology.order.request.OrdersReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author kelvem
 */
@Service
@Slf4j
public class ConvRequest2OrderHandle extends Handle {
    
    @Override
    public void execute() {
    
        OrdersReq req = (OrdersReq) EventContext.getRequest();
        
        // order
        OrdersEntity order = convert(req);
        EventContext.addContext(order);
        
        // orderExtend
        OrderExtendEntity orderExtend = convert(req.getOrderExtend());
        EventContext.addContext(orderExtend);
    
        // address
        List<OrderAddressEntity> addressList = convert(req.getOrderAddressMap());
        EventContext.addContext(addressList);
        
        log.info("Handle[" + getName() + "] order=" + order);
        EventContext.print();
    }
    
    public OrderExtendEntity convert(OrderExtendReq req) {
        OrderExtendEntity entity = new OrderExtendEntity();
        if (req == null) {
            return entity;
        }
        BeanUtils.copyProperties(req, entity);
        return entity;
    }
    
    public OrdersEntity convert(OrdersReq req) {
        OrdersEntity entity = new OrdersEntity();
        BeanUtils.copyProperties(req, entity);
        return entity;
    }
    
    public List<OrderAddressEntity> convert(Map<String, OrderAddressReq> req) {
        
        List<OrderAddressEntity> result = new ArrayList<>();
    
        if (req == null || req.size() <= 0) {
            return result;
        }
        
        for (String addressType:
                req.keySet()) {
            OrderAddressReq addressReq = req.get(addressType);
            OrderAddressEntity entity = new OrderAddressEntity();
            BeanUtils.copyProperties(addressReq, entity);
            entity.setAddressType(addressType);
            result.add(entity);
        }
        return result;
    }
}
